<template>
  <div class="order-detail animate__animated animate__fadeIn">
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <el-page-header @back="goBack" title="返回订单列表">
            <template #content>
              <span class="title">订单详情 - {{ order.orderNum || '加载中...' }}</span>
            </template>
          </el-page-header>
          <div class="actions">
            <el-button 
              type="warning" 
              @click="handleEditStatus"
              icon="Edit"
              v-if="canEditStatus"
              :loading="loading"
            >
              修改物流状态
            </el-button>
            <el-button 
              type="danger" 
              @click="handleDelete"
              icon="Delete"
              v-if="canDelete"
              :loading="loading"
            >
              删除订单
            </el-button>
          </div>
        </div>
      </template>

      <el-skeleton :loading="loading" animated :rows="10">
        <template #default>
          <!-- 订单基本信息 -->
          <el-descriptions :column="2" border class="order-info">
            <el-descriptions-item label="订单编号">{{ order.orderNum || '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ order.userId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="总金额">¥{{ order.total }}</el-descriptions-item>
            <el-descriptions-item label="商品数量">{{ order.amount || 0 }}件</el-descriptions-item>
            <el-descriptions-item label="支付方式">
              {{ paymentMethods[order.method] || order.method || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="物流状态">
              <el-tag :type="getStatusTag(order.Logistics_status)" size="large">
                {{ getStatusText(order.Logistics_status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="收货人">{{ order.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ order.phone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">{{ order.address || '-' }}</el-descriptions-item>
            <el-descriptions-item label="下单时间" :span="2">{{ formatTime(order.orderTime) }}</el-descriptions-item>
            <el-descriptions-item label="备注信息" :span="2">
              {{ order.remark || '无备注' }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 商品信息 -->
          <div class="goods-section">
            <h3 class="section-title">商品信息</h3>
            <el-table :data="order.items" border style="width: 100%" v-loading="itemsLoading">
              <el-table-column label="商品图片" width="120">
                <template #default="{ row }">
                  <el-image 
                    :src="row.goodsImg || 'https://via.placeholder.com/80?text=No+Image'"
                    :preview-src-list="[row.goodsImg]"
                    fit="cover"
                    style="width: 80px; height: 80px;"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称" />
              <el-table-column prop="price" label="单价" width="120">
                <template #default="{ row }">¥{{ row.price }}</template>
              </el-table-column>
              <el-table-column prop="num" label="数量" width="80" />
              <el-table-column label="小计" width="120">
                <template #default="{ row }">¥{{ ((row.price || 0) * (row.num || 0)).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="color" label="颜色" width="120" />
              <el-table-column prop="size" label="尺码" width="120" />
            </el-table>
          </div>
        </template>
      </el-skeleton>
    </el-card>

    <!-- 修改状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      :title="`修改订单状态 - ${order.orderNum}`"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(order.Logistics_status)" size="large">
            {{ getStatusText(order.Logistics_status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select 
            v-model="statusForm.status" 
            placeholder="请选择状态" 
            size="large"
            clearable
          >
            <el-option
              v-for="item in nextStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <!-- 当状态为已发货时，显示物流单号输入框 -->
        <el-form-item label="物流单号" v-if="statusForm.status === '2'">
          <el-input 
            v-model="statusForm.trackingNumber" 
            placeholder="请输入物流单号"
          />
        </el-form-item>
        
        <!-- 所有状态变更都可以添加备注 -->
        <el-form-item label="备注">
          <el-input 
            v-model="statusForm.remark" 
            :placeholder="statusForm.status === '4' ? '请输入取消原因' : '请输入状态变更的备注信息'" 
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmStatusChange" 
          :disabled="!statusForm.status"
          :loading="statusLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAllOrders, getOrderDetail, updateOrderStatus, deleteOrder } from "../../api/order";

// 支付方式映射
const paymentMethods = {
  '1': '支付宝',
  '2': '微信支付',
  '3': '银联',
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  try {
    const date = new Date(time);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
  } catch (e) {
    console.error("时间格式化错误:", e);
    return time;
  }
};

// 获取状态标签类型
const getStatusTag = (status) => {
  switch (status) {
    case '0': return 'info';    // 待支付
    case '1': return 'warning'; // 已支付
    case '2': return 'primary'; // 已发货
    case '3': return 'success'; // 已完成
    case '4': return 'danger';  // 已取消
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待支付';
    case 1: return '已支付';
    case 2: return '已发货';
    case 3: return '已完成';
    case 4: return '已取消';
    default: return '未知状态';
  }
};

// 生成时间线时间戳
const getTimelineDate = (status) => {
  // 如果订单已取消，所有时间都设为订单创建时间
  if (order.value.Logistics_status === '4') {
    return order.value.orderTime;
  }
  
  // 根据状态生成不同的时间
  const baseTime = new Date(order.value.orderTime).getTime();
  switch (status) {
    case 1: // 已支付
      return new Date(baseTime + 1000 * 60 * 5); // 订单创建5分钟后
    case 2: // 已发货
      return new Date(baseTime + 1000 * 60 * 30); // 订单创建30分钟后
    case 3: // 已完成
      return new Date(baseTime + 1000 * 60 * 60); // 订单创建1小时后
    case 4: // 已取消
      return new Date(baseTime + 1000 * 60 * 10); // 订单创建10分钟后
    default:
      return order.value.orderTime;
  }
};

const route = useRoute();
const router = useRouter();
const orderNum = route.params.id; 
// 订单数据结构
const order = ref({
  orderId: '',
  orderNum: '',
  userId: '',
  total: 0,
  amount: 0,
  method: '',
  Logistics_status: '0',
  name: '',
  phone: '',
  address: '',
  orderTime: new Date(),
  items: [],
  remark: '',
});

// 操作日志数据
const operationLogs = ref([]);

// 生成操作日志
const generateOperationLogs = () => {
  const logs = [];
  const currentStatus = parseInt(order.value.Logistics_status);
  
  // 添加订单创建日志
  logs.push({
    time: formatTime(order.value.orderTime),
    operator: '系统',
    action: '创建订单',
    remark: `订单号：${order.value.orderNum}`
  });

  // 根据订单状态添加对应的日志
  if (currentStatus >= 1) {
    logs.push({
      time: formatTime(getTimelineDate(1)),
      operator: '用户',
      action: '支付订单',
      remark: `支付方式：${paymentMethods[order.value.method] || order.value.method || '未知'}`
    });
  }

  if (currentStatus >= 2) {
    logs.push({
      time: formatTime(getTimelineDate(2)),
      operator: '商家',
      action: '发货处理',
      remark: order.value.trackingNumber ? `物流单号：${order.value.trackingNumber}` : '无物流单号'
    });
  }

  if (currentStatus >= 3) {
    logs.push({
      time: formatTime(getTimelineDate(3)),
      operator: '系统',
      action: '完成订单',
      remark: '订单已完成'
    });
  }

  if (currentStatus === 4) {
    logs.push({
      time: formatTime(getTimelineDate(4)),
      operator: order.value.cancelBy || '系统',
      action: '取消订单',
      remark: order.value.cancelReason || '订单已取消'
    });
  }

  operationLogs.value = logs;
};

// 添加新的操作日志
const addOperationLog = (action, remark = '') => {
  operationLogs.value.push({
    time: formatTime(new Date()),
    operator: '管理员',
    action,
    remark
  });
};
const loading = ref(true);
const itemsLoading = ref(false);
const statusLoading = ref(false);
const statusDialogVisible = ref(false);
const statusForm = ref({
  orderNum: '',
  status: '',
  remark: '',
  trackingNumber: ''
});



// 状态选项（只显示可操作的下一步状态）
const nextStatusOptions = computed(() => {
  const currentStatus = order.value.Logistics_status;
  const options = [];
  
  if (currentStatus === '0') {
    options.push({ value: '1', label: '已支付' });
    options.push({ value: '4', label: '已取消' });
  } else if (currentStatus === '1') {
    options.push({ value: '2', label: '已发货' });
    options.push({ value: '4', label: '已取消' });
  } else if (currentStatus === '2') {
    options.push({ value: '3', label: '已完成' });
  }
  
  return options;
});

// 权限控制（根据状态判断）
const canEditStatus = computed(() => nextStatusOptions.value.length > 0);
const canDelete = computed(() => ['0', '4'].includes(order.value.Logistics_status));

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true;
    const response = await getOrderDetail(orderNum);
    console.log('订单详情API响应:', response);
    
    if (response.status === 0 && response.data && response.data.length > 0) {
      // 后端返回的是订单项数组，需要处理成前端需要的格式
      const orderData = response.data[0]; // 获取第一条记录的订单基本信息
      
      // 提取商品项
      const items = response.data.map(item => ({
        goodsId: item.goodsId,
        goodsName: item.goodsName,
        goodsImg: item.goodsImg,
        size: item.size,
        color: item.color,
        price: item.price,
        num: item.num
      }));
      
      // 更新订单信息
      order.value = {
        orderId: orderData.orderId,
        orderNum: orderData.orderNum || '',
        userId: orderData.userId || '',
        total: orderData.total || 0,
        amount: orderData.amount || 0,
        method: orderData.method || '',
        Logistics_status: orderData.Logistics_status || '0',
        name: orderData.name || '',
        phone: orderData.phone || '',
        address: orderData.address || '',
        orderTime: orderData.orderTime || new Date(),
        remark: orderData.remark || '',
        items: items,
      };

      // 生成操作日志
      generateOperationLogs();
    } else {
      ElMessage.error('未找到该订单');
      goBack();
    }
  } catch (error) {
    ElMessage.error("获取订单详情失败: " + (error.message || error));
    console.error("API错误详情:", error);
  } finally {
    loading.value = false;
  }
};





// 修改状态
const handleEditStatus = () => {
  statusForm.value = {
    orderNum: order.value.orderNum,
    status: nextStatusOptions.value[0]?.value || '',
    remark: ''
  };
  statusDialogVisible.value = true;
};

// 确认修改状态
const confirmStatusChange = async () => {
  try {
    statusLoading.value = true;
    
    // 准备请求数据
    const requestData = {
      orderNum: statusForm.value.orderNum,
      Logistics_status: statusForm.value.status
    };
    
    // 如果是已发货状态且有物流单号，添加到请求数据中
    if (statusForm.value.status === '2' && statusForm.value.trackingNumber) {
      requestData.trackingNumber = statusForm.value.trackingNumber;
    }
    
    // 记录原状态
    const oldStatus = getStatusText(order.value.Logistics_status);
    const newStatus = getStatusText(statusForm.value.status);
    
    // 调用API更新状态
    await updateOrderStatus(requestData);
    
    // 更新本地订单数据
    order.value.Logistics_status = statusForm.value.status;
    if (statusForm.value.trackingNumber) {
      order.value.trackingNumber = statusForm.value.trackingNumber;
    }
    
    // 添加操作日志
    let logRemark = `从"${oldStatus}"修改为"${newStatus}"`;
    if (statusForm.value.trackingNumber && statusForm.value.status === '2') {
      logRemark += `，物流单号：${statusForm.value.trackingNumber}`;
    }
    if (statusForm.value.remark) {
      logRemark += ` - ${statusForm.value.remark}`;
    }
    
    addOperationLog('修改订单状态', logRemark);
    
    // 重新生成操作日志
    generateOperationLogs();
    
    ElMessage.success("状态更新成功");
    statusDialogVisible.value = false;
    fetchOrderDetail();
  } catch (error) {
    ElMessage.error(error.message || "状态更新失败");
  } finally {
    statusLoading.value = false;
  }
};

// 删除订单
const handleDelete = () => {
  ElMessageBox.confirm(`确定要删除订单 ${order.value.orderNum} 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      loading.value = true;
      await deleteOrder(order.value.orderNum);
      
      // 添加删除操作日志
      addOperationLog(
        '删除订单',
        `订单号：${order.value.orderNum}，订单状态：${getStatusText(order.value.Logistics_status)}`
      );
      
      ElMessage.success("删除订单成功");
      goBack();
    } catch (error) {
      ElMessage.error(error.message || "删除订单失败");
    } finally {
      loading.value = false;
    }
  });
};

// 返回订单列表
const goBack = () => {
  router.push({ name: 'Order' });
};

onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail {
  padding: 20px;
  min-height: calc(100vh - 40px);
  background-color: #f5f7fa;
}

.detail-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.order-info {
  margin-bottom: 30px;
  background-color: #fff;
}

.goods-section, .logistics-section, .operation-log-section {
  margin-top: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.location {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.logistics-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.current-track {
  border-left: 3px solid #409eff;
  background-color: #f0f7ff;
}

.empty-data {
  padding: 30px 0;
  text-align: center;
}

:deep(.el-descriptions__body) {
  background-color: #fff;
}

:deep(.el-timeline-item__timestamp) {
  color: #606266;
  font-size: 13px;
  font-weight: 500;
}

:deep(.el-timeline-item.current-track .el-timeline-item__content) {
  background-color: #f0f7ff;
  padding: 10px 15px;
  border-radius: 4px;
}

:deep(.el-timeline-item.current-track h4) {
  margin: 0;
  font-weight: bold;
  color: #409eff;
}

.actions {
  display: flex;
  gap: 10px;
}
</style>